package com.example.temp.controller;

import com.example.temp.common.Result;
import com.example.temp.entity.Role;
import com.example.temp.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleMapper roleMapper;

    @GetMapping("/all")
    public Result getAllRoles() {
        List<Role> roles = roleMapper.findAll();
        return Result.success(roles);
    }

    @GetMapping("/{id}")
    public Result getRoleById(@PathVariable Integer id) {
        Role role = roleMapper.findById(id);
        return Result.success(role);
    }
    
    @PostMapping("/add")
    public Result addRole(@RequestBody Role role) {
        try {
            // 验证角色ID是否已存在
            Role existingRole = roleMapper.findById(role.getId());
            if (existingRole != null) {
                return Result.fail("角色ID已存在");
            }
            
            int result = roleMapper.addRole(role);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.fail("添加角色失败");
            }
        } catch (Exception e) {
            return Result.fail("添加角色失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/update")
    public Result updateRole(@RequestBody Role role) {
        try {
            int result = roleMapper.updateRole(role);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.fail("更新角色失败");
            }
        } catch (Exception e) {
            return Result.fail("更新角色失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/delete/{id}")
    public Result deleteRole(@PathVariable Integer id) {
        try {
            // 检查系统是否依赖该角色
            if (id <= 2) { // 基本角色(0=管理员,1=教师,2=学生)不允许删除
                return Result.fail("不允许删除系统基本角色");
            }
            
            int result = roleMapper.deleteRole(id);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.fail("删除角色失败");
            }
        } catch (Exception e) {
            return Result.fail("删除角色失败: " + e.getMessage());
        }
    }
}
